package com.facebook;

import com.facebook.Facebook.DialogListener;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

public class FbMgr {
	static final String APP_ID = "187466994621698";
	Facebook fb;
	FbAuthorizeListener fbAuthorizeListener;
	FbLogoutListener fbLogoutListener;
	Handler handler = new Handler();
	Activity activity;
	

	public FbMgr(Activity activity) {
		this.activity = activity;
		fb = new Facebook(APP_ID);
	}

	
	public void fbAuthorize(FbAuthorizeListener fbAuthorizeListener) {
		this.fbAuthorizeListener = fbAuthorizeListener;
		fb.authorize(activity, new String[] {}, new LoginDialogListener());
	}


	class LoginDialogListener implements DialogListener {
		public void onComplete(Bundle values) {
			fbAuthorizeListener.onFbAuthorizeComplete();
		}

		public void onError(DialogError error) {
			Toast.makeText(activity, "loading facebook authorization page failed, try again later", Toast.LENGTH_LONG).show();
		}
		
		public void onCancel() {
		}

		public void onFacebookError(FacebookError error) {
		}
	}

	
	public void fbLogout(FbLogoutListener fbLogoutListener) {
		this.fbLogoutListener = fbLogoutListener;
		AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(fb);
		asyncRunner.logout(activity, new LogoutRequestListener());
	}


	class LogoutRequestListener extends BaseRequestListener {
		public void onComplete(String response, final Object state) {
			handler.post(new Runnable() {
				public void run() {
					fbLogoutListener.onFbLogoutComplete();
				}
			});
		}
	}

	
	public String request(String reqStr) {
		String result = null;
		try {
			result = fb.request(reqStr);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return result;
	}
}
